import axios from 'axios'
import qs from 'querystring'
import { message } from 'antd'
import NProgress from 'nprogress'
import store from '../store'

import { deleteUserAction } from '../store/actionCreators/login'
import { selectNavAction } from '../store/actionCreators/admin'
import 'nprogress/nprogress.css'

const ajax = axios.create({
  baseURL: 'http://localhost:3000',
})

ajax.interceptors.request.use((config) => {
  NProgress.start()
  const { method, data } = config

  // 配置token
  let { token } = store.getState().userInfo
  if (token) {
    config.headers.Authorization = 'atguigu_' + token
  }

  if (method.toLocaleLowerCase() === 'post' && data instanceof Object) {
    config.data = qs.stringify(data)
  }

  return config

}, (err) => {
  console.log(err)
})



ajax.interceptors.response.use((response) => {
  NProgress.done()
  return response.data
}, (err) => {
  NProgress.done()
  if (err.response.status === 401) {
    message.error('身份过期,请重新登陆!')
    store.dispatch(deleteUserAction())
    store.dispatch(selectNavAction(''))
  } else {
    message.error(err.message)
  }

  return new Promise(() => { })
})

export default ajax








